package packutil;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

	// TODO: test cases for this!!
	public static int diffInDays(Date d1, Date d2) {

		final int millisPerDay = 1000 * 60 * 60 * 24;

		// set times to 0
		d1 = resetTime(d1);
		d2 = resetTime(d2);
		double diff = ((double) (d2.getTime() - d1.getTime())) / millisPerDay;

		return (int) Math.round(diff);
	}

	public static Date today() {
		return resetTime(new Date());
	}

	/**
	 * Sets hour, minute, second, millis to 0 for this date
	 */
	public static Date resetTime(Date d) {
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		return c.getTime();
	}

	/**
	 * Sets hour (0-23), minute, second, millsec for this date
	 */
	public static Date resetTime(Date d, int hour, int minute, int second,
			int millisec) {
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.set(Calendar.HOUR_OF_DAY, hour);
		c.set(Calendar.MINUTE, minute);
		c.set(Calendar.SECOND, second);
		c.set(Calendar.MILLISECOND, millisec);
		return c.getTime();
	}

	public static Date adjustMinutes(Date date, int minutes) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.MINUTE, minutes);
		return c.getTime();
	}

	public static Date adjustDays(Date date, int days) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.DATE, days);
		return c.getTime();
	}

	public static Date parseDate(String date, String format) {

		SimpleDateFormat df = new SimpleDateFormat(format);
		try {
			return df.parse(date);
		} catch (Exception e) {
			throw new RuntimeException("Couldn't parse date[" + date
					+ "] to format[" + format + "]", e);
		}
	}

	public static String formatDate(Date date, String format) {

		SimpleDateFormat df = new SimpleDateFormat(format);
		try {
			return df.format(date);
		} catch (Exception e) {
			throw new RuntimeException("Couldn't parse date[" + date
					+ "] to format[" + format + "]", e);
		}
	}

}
